package com.xy.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

import static org.apache.zookeeper.ZooDefs.Ids.OPEN_ACL_UNSAFE;

public class ZkCreate {
    private static ZooKeeper zk;
    private static ZooKeeperConnection conn;

    public static void create(String path, byte[] data) throws KeeperException, InterruptedException {
        zk.create(path, data, OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    public static Stat exist(String path) throws KeeperException, InterruptedException {
        return zk.exists(path, true);
    }

    public static void main(String[] args) {
        String path = "/MyFirstZnode";
        final CountDownLatch connectedSignal = new CountDownLatch(3);
        try {
            conn = new ZooKeeperConnection();
            zk = conn.connect("localhost");
            Stat stat = exist(path);

            if(stat != null) {
                byte[] b = zk.getData(path, new Watcher() {

                    @Override
                    public void process(WatchedEvent we) {

                        if (we.getType() == Event.EventType.None) {
                            switch(we.getState()) {
                                case Expired:
                                    connectedSignal.countDown();
                                    break;
                            }

                        } else {
                            String path = "/MyFirstZnode";

                            try {
                                byte[] bn = zk.getData(path,
                                        false, null);
                                String data = new String(bn,
                                        "UTF-8");
                                System.out.println(data);
                                connectedSignal.countDown();

                            } catch(Exception ex) {
                                System.out.println(ex.getMessage());
                            }
                        }
                    }
                }, null);

                String data = new String(b, "UTF-8");
                System.out.println(data);
                connectedSignal.await();

            } else {
                System.out.println("Node does not exists");
            }
        } catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
